import type { Directive, DirectiveBinding } from 'vue'
import { useAppStore } from '@/stores'

interface PermissionValue {
  menuPath?: string
  permission?: 'read' | 'write' | 'create' | 'update' | 'delete'
  action?: 'hide' | 'disable'
}

// 检查权限的函数
function checkPermission(value: string | PermissionValue): boolean {
  const appStore = useAppStore()



  // 如果用户未登录，没有任何权限
  if (!appStore.userInfo) {
    console.log('❌ 用户未登录，无权限')
    return false
  }

  // 超级管理员拥有所有权限
  if (appStore.userInfo.is_superuser) {
    console.log('✅ 超级管理员，拥有所有权限')
    return true
  }

  let permission = 'read'

  if (typeof value === 'string') {
    permission = value
  } else if (value.permission) {
    permission = value.permission
  }

  console.log('🎯 检查权限类型:', permission)

  // 权限检查逻辑
  if (permission === 'write' || permission === 'create' ||
    permission === 'update' || permission === 'delete') {
    // 写权限需要是管理员或超级管理员
    const hasWritePermission = appStore.userInfo.is_staff || appStore.userInfo.is_superuser
    console.log('📝 写权限检查结果:', {
      is_staff: appStore.userInfo.is_staff,
      is_superuser: appStore.userInfo.is_superuser,
      hasWritePermission
    })
    return hasWritePermission
  }

  // 读权限允许已登录用户
  if (permission === 'read') {
    console.log('👀 读权限，允许已登录用户')
    return true
  }

  // 默认无权限
  console.log('🚫 默认无权限')
  return false
}

// 权限指令
export const vPermission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding



    if (!value) {
      console.warn('v-permission 指令需要提供权限值')
      return
    }

    // 多次检查权限，确保用户信息已加载
    const checkAndApplyPermission = () => {
      const hasPermission = checkPermission(value)

      if (!hasPermission) {
        const action = typeof value === 'object' && value.action ? value.action : 'hide'

        if (action === 'hide') {
          // 隐藏元素
          el.style.display = 'none'
        } else if (action === 'disable') {
          // 禁用元素
          el.setAttribute('disabled', 'true')
          el.style.opacity = '0.5'
          el.style.cursor = 'not-allowed'

          // 阻止点击事件
          el.addEventListener('click', (e) => {
            e.preventDefault()
            e.stopPropagation()
          }, true)
        }
      }
    }

    // 立即检查一次
    checkAndApplyPermission()

    // 延迟检查，确保用户信息已加载
    setTimeout(checkAndApplyPermission, 200)
    setTimeout(checkAndApplyPermission, 500)
  },

  updated(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding

    if (!value) {
      return
    }

    const hasPermission = checkPermission(value)

    if (!hasPermission) {
      const action = typeof value === 'object' && value.action ? value.action : 'hide'

      if (action === 'hide') {
        el.style.display = 'none'
      } else if (action === 'disable') {
        el.setAttribute('disabled', 'true')
        el.style.opacity = '0.5'
        el.style.cursor = 'not-allowed'
      }
    } else {
      // 恢复元素状态
      el.style.display = ''
      el.removeAttribute('disabled')
      el.style.opacity = ''
      el.style.cursor = ''
    }
  }
}

// 权限检查组合式函数
export function usePermission() {
  const appStore = useAppStore()

  const canRead = (menuPath?: string): boolean => {
    // 如果用户未登录，没有任何权限
    if (!appStore.userInfo) return false

    // 超级管理员拥有所有权限
    if (appStore.userInfo.is_superuser) return true

    // 已登录用户有读权限
    return true
  }

  const canWrite = (menuPath?: string): boolean => {
    // 如果用户未登录，没有任何权限
    if (!appStore.userInfo) return false

    // 超级管理员拥有所有权限
    if (appStore.userInfo.is_superuser) return true

    // 只有管理员有写权限
    return appStore.userInfo.is_staff || false
  }

  const canPerformAction = (menuPath: string, action: 'read' | 'write' | 'create' | 'update' | 'delete'): boolean => {
    if (action === 'read') {
      return canRead(menuPath)
    } else {
      return canWrite(menuPath)
    }
  }

  return {
    canRead,
    canWrite,
    canPerformAction
  }
}
